package com.hicampus.portlet.verifycontact;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.io.IOUtils;

public class MaxMindUtil {
	
	private static final String maxMindLoginId = "CDqrS3xVS6Xx";
	
	public static GeoLocation getLocation(String ipAddress) {
		
		String url = "http://geoip3.maxmind.com/b?l=" + maxMindLoginId + "&i=" + ipAddress;
		
		GeoLocation location = null;
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod(url);
		
		try {
			client.executeMethod(method);
			
			InputStream is = method.getResponseBodyAsStream();

			String data = IOUtils.toString(is);
			location = new GeoLocation(data);

			is.close();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
	
		return location;
	}
	
	public static void dialNumber(String contactNumber, String generatedPIN) {
		String url = "https://www.maxmind.com/app/telephone_http?l=" + maxMindLoginId + "&phone=%2B" + contactNumber + "&verify_code=" + generatedPIN;
		
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod(url);
		
		try {
			client.executeMethod(method);
			
			InputStream is = method.getResponseBodyAsStream();
			
			is.close();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
	}
}
